/*
 * Copyright © 2011 by PropSage Pte Ltd. 
 * All Rights Reserved.
 * licensing@propsage.com
 * http://www.propsage.com/terms.html
 * 
 * 
 * Javascript for /case/index
 * 
 * @author Poh Nean
 * @modified Meng Lei
 */
propsage.namespace("prestige.receipt");

prestige.receipt.update = (function($, ui){
	function initEventHandlers() {
		$("#Receipt_payer_name").blur(onPayerNameBlur);
		
		$('#Receipt_payment_method_type_code').on('change', onPaymentMethodTypeCodeChange);
		
		$('#invoices').on('change', '#payment_application_grid_cid_all', onCheckAllChange);
		
		$('#invoices').on("change", ".invoicecol-check :checkbox", onApplyPaymentCheckboxChange);
		// trigger partial payment
		$('#invoices').on("keyup", ".invoicecol-amount-applied input:text", onAmountAppliedTextChange);
		
		$('#btnFinish').click(onBtnFinishClick);
	}
	
	function onBtnFinishClick(e) {	
		e.stopImmediatePropagation();
		
		var amountApplied = 0, amountReceived = 0, amountRemaining;
		
		amountReceived = $('#Receipt_amount').autoNumeric('get');
		amountApplied = getTotalAmountApplied();
		amountRemaining = amountReceived - amountApplied;
		
		var isValid = $('#add-receipt-form').yiiactiveform2("validate");
		
		if (isValid) {
			var continueSubmit = true;
			if (amountRemaining > 0) {
				continueSubmit = window.confirm('You have $' + amountRemaining.toFixed(2) + ' not applied to any invoice. Do you want to continue saving receipt?');
			}
			if (continueSubmit) {
				$('#add-receipt-form').submit();
			}
		} else {
			return false;
		}
	}
	
	function onPaymentMethodTypeCodeChange() {
		var val = $(this).val();
            
		if (val == 'Other') {
			$('#Receipt_payment_method_other').show().val('');
		} else {
			$('#Receipt_payment_method_other').hide().val('');
		}
	}
	
	function onAmountAppliedTextChange(event) {
		var $this = $(this),
		amountApplied = $(this).val(),
		$row = $this.closest('tr'),
		$invoiceBalance = $row.find('.invoice_balance'),
		amountDue = null,
		$validate = false,
		temp = null;
		
			
		temp = $invoiceBalance.val();
		amountDue = parseFloat(temp.replace(/[$,]+/g,""));
		amountApplied = parseFloat(amountApplied.replace(/[$,]+/g,""));
		
		if(amountApplied >= amountDue) {
			$row.find('.invoicecol-check :checkbox').prop('checked', true);
		} else {
			$row.find('.invoicecol-check :checkbox').prop('checked', false);
		}
		
		updatePaymentAmount();
	}
	
	function validateAmountApplied(amountApplied, amountDue) {
		
		return (amountApplied > amountDue);
	}
	
	function onApplyPaymentCheckboxChange(event) {		
		var $this = $(this), 
		$row = $this.closest('tr'),
		$amountAppliedInput = $row.find('.invoicecol-amount-applied input'),
		$invoiceBalance = $row.find('.invoice_balance');
		
		if($this.is('#payment_application_grid_cid_all')) {
			if($this.is(':checked')) {
				$('#btnReceiveAll').trigger('click');
			} else {
				resetReceiveAll();
			}
		} else {
			if ($this.is(':checked')) {
				// check empty object
				if($invoiceBalance.length > 0) {
					$amountAppliedInput.autoNumeric('set', $invoiceBalance.val());
				}
					
			} else {
				$amountAppliedInput.autoNumeric('set', 0);
			}

			updatePaymentAmount();
		}

	}
	
	/**
	 * check all checkbox and update the amount to payment amount
	 */
	function onCheckAllChange(event) {
		var checked = $(this).prop('checked');
		
		$('#payment_application_grid input.invoice_balance').each(function() {
			var $this = $(this), $row = $this.closest('tr');
			$row.find('input.amount_applied').autoNumeric('set', $this.val());
			$row.find('.invoicecol-check :checkbox').prop('checked', checked);
		});
		
		updatePaymentAmount();
	}
	
	/**
	 * uncheck all the checkbox and reset the balance amount
	 */
	function resetReceiveAll() {
		$('#payment_application_grid_cid_all').prop('checked', false);
		$('#payment_application_grid input.invoice_balance').each(function() {
			var $this = $(this), $row = $this.closest('tr');
			$row.find('input.amount_applied').autoNumeric('set', 0);
		});
		
		updatePaymentAmount();
	}
	
	function onPayerNameBlur(event) {
		var payerName = $('#Receipt_payer_name').val();
		if (payerName == '') {
			$(this).val('');
			$('#Receipt_payer_party_id').val('');
			$('#Receipt_contact_id').val('');
		}
	}
	
	function onPartySelected(event, ui) {
		$('#Receipt_payer_party_id').val('');
		if (ui.item.party_id) {
			$('#Receipt_payer_party_id').val(ui.item.party_id);
		}
				
		$('#Receipt_contact_id').val('');
		if (ui.item.category == 'Contacts' && ui.item.id) {
			$('#Receipt_contact_id').val(ui.item.id);
		}
		
		loadOpenInvoices(ui.item.party_id);
	}
	
	function loadOpenInvoices(partyId) {
		$.fn.yiiGridView.update("payment_application_grid", {
			data: {
				party_id: partyId
			}
		});
	}
	
	function onGridViewUpdate() {		
		$('#payment_application_grid input.amount_applied').each(function() {
			$(this).autoNumeric();
		});
	}
	
	function getTotalAmountApplied() {
		var totalAmountApplied = 0, amount = 0;
		$('#payment_application_grid input.amount_applied').each(function() {
			amount = parseFloat($(this).autoNumeric('get'));
			totalAmountApplied += amount;
		});
		
		return totalAmountApplied;
	}
	
	function updatePaymentAmount() {
		var total = getTotalAmountApplied();
		
		if (total > 0) {
			$('#Receipt_amount').autoNumeric('set', total);
		} else {
			$('#Receipt_amount').autoNumeric('set', 0);
		}
	}
    
	$(document).ready(function(){
		initEventHandlers();
		onGridViewUpdate();
	});
	
	return {
		onPartySelected: onPartySelected,
		onGridViewUpdate: onGridViewUpdate
	}
    
}(jQuery, propsage.ui));